<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="50%"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from './menu.data';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';

  import { getMenuList, createMenu, updateMenu } from '/@/api/demo/system';
  import { useMessage } from '/@/hooks/web/useMessage';

  export default defineComponent({
    name: 'MenuDrawer',
    components: { BasicDrawer, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      let treeData

      const { createMessage } = useMessage();

      const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
        labelWidth: 100,
        schemas: formSchema,
        showActionButtonGroup: false,
        baseColProps: { lg: 12, md: 24 },
      });

      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        resetFields();
        setDrawerProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;

        if (unref(isUpdate)) {
          setFieldsValue({
            ...data.record,
          });
        }
        treeData = await getMenuList();
        updateSchema({
          field: 'parentId',
          componentProps: { treeData },
        });
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增菜单' : '编辑菜单'));

      async function handleSubmit() {
        try {
          const formData = await validate();
          setDrawerProps({ confirmLoading: true });
          // TODO custom api
          // formData.parentId = formData.parentMenu ? parseInt(formData.parentMenu) : 0;
          formData.parentId = formData.parentId ? parseInt(formData.parentId) : 0;
          formData.id = treeData.find((item) => item.name === formData.name)?.id;
          formData.active = parseInt(formData.active)
          formData.acl = "read,create,delete,update,manage"
          formData.redirect = formData.redirect ? formData.redirect : ""
          // console.log(formData);
          // console.log("🚀 ~ handleSubmit ~ isUpdate:", unref(isUpdate))
          if (!unref(isUpdate)) {
            await createMenu(formData);
          } else {
            if (formData.active == 0) {
              // 判断所有子菜单全部关闭后，主菜单才能关闭
              if (checkAllChindrenMenuDisabled(formData.id)) await updateMenu(formData);
              else return createMessage.error('子菜单未全部禁用，不能禁用主菜单');
            } else {
              await updateMenu(formData);
            }
          }
          closeDrawer();
          emit('success');
        } finally {
          setDrawerProps({ confirmLoading: false });
        }
      }

      function checkAllChindrenMenuDisabled(id: number){
        const subMenu = treeData.filter(item => item.parentId === id)
        if (subMenu.length === 0) return true;
        let flag = true;
        subMenu.forEach(item => {
          if (!checkAllChindrenMenuDisabled(item.id)) flag = false;
          if (item.active === 1) flag = false;
        })
        return flag;
      }
      return { registerDrawer, registerForm, getTitle, handleSubmit };
    },
  });
</script>
